import React, { useEffect, useState } from 'react';
import { message, Space, Table, Tag } from 'antd';
import type { TableProps } from 'antd';
import instance from '../../api/request';
import { Button, Modal, Form, Input, Drawer } from 'antd';
import type { TableRowSelection } from 'antd/es/table/interface';
import { useNavigate } from 'react-router-dom';


interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}

function Index() {
  const [data, setdata] = useState([])

  const [count, setcount] = useState(0)
  const [page, setpage] = useState(1)
  const [pageSize, setpageSize] = useState(6)
  const getdata = () => {
    instance.get('/api/article/list', {
      params: {
        page: page,
        pageSize: pageSize
      }
    }).then(res => {
      setdata(res.data.rows)
      setcount(res.data.count)
    })
  }
  useEffect(() => {
    getdata()
  }, [page, pageSize])
  // 分页
  const change = (page, pageSize) => {
    setpage(page)
    setpageSize(pageSize)

  }
  // 搜索
  const { Search } = Input;
  const onSearch = (value) => {
    setCzs(value)
    instance.get('/api/article/list', {
      params: {
        keyword: value,//搜索标题
        page: 1,
      }
    }).then(res => {
      setdata(res.data.rows)
      setcount(res.data.count)
    })
  }

  // 删除
  const del = (record) => {
    setdata((prev) => prev.filter((item) => item.id !== record.id))
  }
  // 批量删除
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const plsc = () => {
    const sclist = data.filter((item) => !selectedRowKeys.includes(item.id))
    setdata(sclist)
    message.success('删除成功')
  }
  // 新增
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm()
  const [title1, settilte1] = useState('')

  const [edit, setedit] = useState('')
  const add = () => {
    setIsModalOpen(true);
    form.resetFields()
    settilte1('新增')
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const onFinish = (values) => {
    if (title1 == '新增') {
      instance.post('/api/article', {
        "title": values.title,//文章标题
        "content": values.content,//文章内容
        "tagList": ["HTTP"],//标签  array[string]
        "categoryList": ["HTTP"],//分类  array[string]
        "authorId": 47529555//用户id 暂时写死47529555 登陆成功后返回的用户信息
      }
      ).then(res => {
        alert('新增成功')
        setIsModalOpen(false);
        getdata()
      })
    } else {
      instance.put(`/api/article/${edit}`, { ...values, id: edit }).then(res => {
        alert('编辑成功')
        setIsModalOpen(false)
        getdata()
      })

    };

    // 编辑
  }
  const bj = (record) => {
    settilte1('编辑')
    form.setFieldsValue(edit)
    setIsModalOpen(true);
    setedit(record.id)
  }


  // 详情
  const [open, setOpen] = useState(false);
  const [detail, setDetail] = useState({})
  const xq = async (id) => {
    // navigate(`/home/order/${id}`)
    setOpen(true);
    const res = await instance.get(`/api/article/${id}`)
    console.log(res);
    setDetail(res.data)

  }
  const onClose = () => {
    setOpen(false);
  };


  // 支付
  const gopay = () => {
    const resault = instance.post('/api/order/alipay', {
      "orderNo": "accfd131-86c7-484c-9e69-66d1b3f70286",//订单id
      "totalPrice": 29.99,//价格
      "subject": "解锁文章" //支付描述

    }).then(res => {
      console.log(res);
      window.open(res.data.url)
    })
    console.log(resault);

  }
  const columns: TableProps<DataType>['columns'] = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      render: (text) => <a>{text}</a>,
    },
    {
      title: 'createdAt',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: 'viewCount',
      dataIndex: 'viewCount',
      key: 'viewCount',
    },
    {
      title: 'content',
      dataIndex: 'content',
      key: 'content',
    },
    {
      title: 'title',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: 'Action',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => bj(record)}>编辑</a>
          <a onClick={() => del(record)}>删除</a>
          <a onClick={() => xq(record.id)}>详情</a>
        </Space>
      ),
    },
  ];



  // 重置
  const [czs, setCzs] = useState('')
  const cz = () => {
    setCzs('')

    getdata()
    setpage(1)
  }
  return (

    <div>
      <h2>列表数据</h2>
      <button>增删改查</button>

      <p>呜呜呜</p>


      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}

        autoComplete="off"
      >
        <Search placeholder="input search text" onSearch={onSearch}

          value={czs}
          onChange={(e) => setCzs(e.target.value)}
          style={{ width: 200 }} />

        <Button type="primary" onClick={plsc}>批量删除</Button>

        <Button type="primary" onClick={add}>
          新增
        </Button>

        <Button type="primary" onClick={cz}>
          重置
        </Button>
        <Modal
          title={title1}
          closable={{ 'aria-label': 'Custom Close Button' }}
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <Form
            form={form}
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}

            autoComplete="off"
          >
            <Form.Item
              label="title"
              name="title"
              rules={[{ required: true, message: 'Please input your username!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="content"
              name="content"
              rules={[{ required: true, message: 'Please input your username!' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item label={null}>
              <Button type="primary" htmlType="submit">
                Submit
              </Button>
            </Form.Item>
          </Form>
        </Modal>

      </Form>

      <Drawer
        title="详情"
        closable={{ 'aria-label': 'Close Button' }}
        onClose={onClose}
        open={open}
      >
        {
          detail && <div>
            <p>{detail.id}</p>
            <p>{detail.title}</p>
            <p>{detail.content}</p>
            <p>{detail.createdAt}</p>
            <p>{detail.updatedAt}</p>
            <p>价格：{detail.viewCount}</p>
          </div>
        }
        <Button onClick={gopay}>支付</Button>
      </Drawer>
      <Table<DataType> columns={columns} dataSource={data}
        rowSelection={rowSelection}
        rowKey={'id'}
        pagination={
          {
            total: count,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `Total ${total} items`,
            onChange: change
          }
        }

      />
    </div>
  )

}

export default Index;